package com.itheima.web;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.*;
import com.itheima.service.BookService;
import com.itheima.service.impl.BookServiceImpl;
import com.itheima.web.base.BaseServlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/book/*")
public class BookServlet extends BaseServlet {
    BookService service = new BookServiceImpl();

    /**
     * 查询所有图书
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectAll(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Book> books = service.selectAll();

        String s = JSON.toJSONString(books);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(s);
    }

    /**
     * 增加图书
     * @param request
     * @param response
     * @throws Exception
     */
    public void add(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader reader = request.getReader();
        String s = reader.readLine();
        System.out.println(s);
        Book book = JSON.parseObject(s, Book.class);
        System.out.println(book);

        boolean flag = service.add(book);
        if (flag){
            response.getWriter().write("success");
        }else {
            response.getWriter().write("lose");
        }

    }

    /**
     * 批量删除图书
     * @param request
     * @param response
     * @throws Exception
     */
    public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws Exception{
        BufferedReader reader = request.getReader();
        String params = reader.readLine();

        //转为数组
        int[]  ids = JSON.parseObject(params, int[].class);

        service.deleteByIds(ids);

        response.getWriter().write("success");
    }

    /**
     * 分页查询
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        PageBean<Book> pageBean = service.selectByPage(currentPage, pageSize);

        String s = JSON.toJSONString(pageBean);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(s);
    }

    /**
     * 分页条件查询
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String _currentPage = request.getParameter("currentPage");
        String _pageSize = request.getParameter("pageSize");

        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);

        BufferedReader reader = request.getReader();
        String params = reader.readLine();

        //转为book对象
        Book book = JSON.parseObject(params, Book.class);
 /*       if (book == null) {
            book = new Book();
        }*/

        PageBean<Book> pageBean = service.selectByPageAndCondition(currentPage, pageSize,book);

        String s = JSON.toJSONString(pageBean);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(s);
    }

    /**
     * 删除
     * @param request
     * @param response
     * @throws Exception
     */
    public void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader reader = request.getReader();
        String params = reader.readLine();
        System.out.println("---------"+params+"---------");

        //接收的id转为整型
        Integer id = JSON.parseObject(params, Integer.class);

        service.delete(id);

        response.getWriter().write("success");

    }

    /**
     * 编辑数据时传过来的id
     * @param request
     * @param response
     * @throws Exception
     */
    public void acceptId(HttpServletRequest request, HttpServletResponse response) throws Exception{
        BufferedReader reader = request.getReader();
        String params = reader.readLine();

        Integer acceptId = JSON.parseObject(params, Integer.class);

        HttpSession session = request.getSession();
        session.setAttribute("acceptId",acceptId);

        response.getWriter().write("success");



    }

    /***
     * 编辑图书
     * @param request
     * @param response
     * @throws Exception
     */
    public void update(HttpServletRequest request, HttpServletResponse response) throws Exception{
        BufferedReader reader = request.getReader();
        String params = reader.readLine();

        HttpSession session = request.getSession();
        Integer  acceptId = (Integer)session.getAttribute("acceptId");
        System.out.println(acceptId);

        Book book = JSON.parseObject(params, Book.class);


        book.setId(acceptId);
        System.out.println(book);

        int i = service.update(book);
        if (i>0){
            response.getWriter().write("success");
        }else {
            response.getWriter().write("lose");
        }


    }

    /**
     * 借书
     * @param request
     * @param response
     * @throws Exception
     */
    public void borrow(HttpServletRequest request, HttpServletResponse response) throws Exception{
        BufferedReader reader = request.getReader();
        String params = reader.readLine();

        HttpSession session = request.getSession();
        Integer  acceptId = (Integer)session.getAttribute("acceptId");
        System.out.println(acceptId);

        Borrow borrow = JSON.parseObject(params, Borrow.class);
        System.out.println(borrow);

        //获取浏览器传过来的还书日期（国际时间）
        String time = borrow.getTime();
        time = time.replace("Z", " UTC");

        //把时间格式化为北京时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date parse = format.parse(time);
        String result = sdf.format(parse);
        borrow.setTime(result);//把还书日期格式化为北京时间存进borrow对象

        String username = borrow.getUsername();
        String name = borrow.getName();

        //获取现在的时间并格式化为字符串
        Date date = new Date();
        String borrowTime = sdf.format(date);

        //借书历史记录
        History history = new History();
        history.setUsername(username);
        history.setName(name);
        history.setBorrowTime(borrowTime);
        history.setTime(result);

        //生成借书历史记录
        boolean flag = service.addHistory(history);

        //通过id查找要借的书的库存
        Book book = service.selectById(acceptId);
        int num = book.getPnum();

        if (num>0&&flag){
            book.setPnum(num-1);
            service.update(book);
            service.borrow(borrow);
            response.getWriter().write("success");
        }else {
            response.getWriter().write("lose");
        }

    }


    /**
     * 还书
     * @param request
     * @param response
     * @throws Exception
     */
    public void revert(HttpServletRequest request, HttpServletResponse response) throws Exception{
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String username = user.getUsername();
        System.out.println(username);

        List<Borrow> list = service.selectByUsername(username);
        System.out.println(list);

        Date data = new Date();
        long now = data.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (Borrow borrow : list) {
            String time = borrow.getTime();
            long huan = sdf.parse(time).getTime();

            if (now<=huan){
                borrow.setOvertime("否");
            }else {
                borrow.setOvertime("是");
            }

        }

        String s = JSON.toJSONString(list);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(s);

    }

    /**
     * 根据id删除借书记录
     * @param request
     * @param response
     * @throws Exception
     */
    public void deleteBorrow(HttpServletRequest request, HttpServletResponse response) throws Exception{
        BufferedReader reader = request.getReader();
        String params = reader.readLine();
        System.out.println("---------"+params+"---------");

        //接收的id转为整型
        Integer id = JSON.parseObject(params, Integer.class);


        Borrow borrow = service.getBook(id);
        String name = borrow.getName();

        Book book = service.selectByName(name);
        book.setPnum(book.getPnum()+1);

        service.update(book);

        service.deleteBorrow(id);

        response.getWriter().write("success");

    }

    /**
     * 还书时个人借书记录的显示
     * @param request
     * @param response
     * @throws Exception
     */
    public void selectBorrow(HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<Borrow> list = service.selectFromBorrow();

        Date data = new Date();
        long now = data.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (Borrow borrow : list) {
            String time = borrow.getTime();
            long huan = sdf.parse(time).getTime();

            if (now<=huan){
                borrow.setOvertime("否");
            }else {
                borrow.setOvertime("是");
            }

        }

        String s = JSON.toJSONString(list);

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(s);
    }

}
